<?php

namespace plugin\ycMassage\app\shop\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageMchThumb;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\app\model\MassageShopThumb;
use plugin\ycMassage\app\validate\MassageMch as ValidateMassageMch;
use plugin\ycMassage\app\validate\MassageShop as ValidateMassageShop;
use plugin\ycMassage\utils\enum\Examine;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use plugin\ycMassage\utils\AMap;
use support\Request;
use think\facade\Db;

class UserController extends BaseController
{
    public function editSelf(Request $request)
    {
        if ($request->use_mch_id) {
            return $this->buildMch($request);
        } else {
            return $this->buildShop($request);
        }
    }
    public function buildMch(Request $request)
    {
        $MassageMch = MassageMch::where(['id' => $request->use_mch_id])->find();
        if (!$MassageMch) {
            return $this->fail('商户不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $tel = [];
            if ($D['tel1']) {
                $tel[] = $D['tel1'];
            }
            if ($D['tel2']) {
                $tel[] = $D['tel2'];
            }
            if ($D['tel3']) {
                $tel[] = $D['tel3'];
            }
            $D['tel'] = $tel;
            hpValidate(ValidateMassageMch::class, $D, 'admin_update');
            Db::startTrans();
            try {
                $MassageMch->title = $D['title'];
                $MassageMch->logo = $D['logo'][0];
                $MassageMch->address = $D['address'];
                $MassageMch->name = $D['name'];
                $MassageMch->mobile = $D['mobile'];
                $MassageMch->tel = $tel;
                list($province_id, $city_id, $area_id, $street_id) = $D['regions'];
                $MassageMch->province_id = (int)$province_id;
                $MassageMch->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageMch->city_id = $city_id;
                $MassageMch->city = MassageRegions::where(['id' => $city_id])->value('title');
                $MassageMch->area_id = $area_id;
                $MassageMch->area = MassageRegions::where(['id' => $area_id])->value('title');
                if ($street_id) {
                    $MassageMch->street_id = $street_id;
                    $MassageMch->street = MassageRegions::where(['id' => $street_id])->value('title');
                } else {
                    $MassageMch->street_id = null;
                    $MassageMch->street = '';
                }
                Db::commit();
                return $this->success('保存成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('title', 'input', '商户名称', '', [
            'col' => 12,
        ]);
        $builder->addComponent('logo', 'uploadify', '商户logo', '', [
            'col' => 12,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('tel1', 'input', '商户联系电话1', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel2', 'input', '商户联系电话2', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel3', 'input', '商户联系电话3', '', [
            'col' => 12,
        ]);
        $regions = MassageRegions::getCache($request->saas_appid);
        $builder->addRow('regions', 'city', '地区', [], [
            'col' => 12,
            'options' => $regions,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ]
        ]);
        $builder->addRow('address', 'input', '详细地址', '', [
            'col' => 12,
        ]);
        $builder->addDivider('负责人信息');
        $builder->addRow('name', 'input', '负责人', '', [
            'col' => 12,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
        ]);
        $regions = [
            $MassageMch->province_id,
            $MassageMch->city_id,
            $MassageMch->area_id
        ];
        if ($MassageMch->street_id) {
            $regions[] = $MassageMch->street_id;
        }
        $MassageMch->regions = $regions;
        foreach ($MassageMch->tel as $key => $value) {
            $MassageMch->{'tel' . ($key + 1)} = $value;
        }
        $data = $builder->setData($MassageMch)->create();
        return $this->successRes($data);
    }
    public function buildShop(Request $request)
    {
        $saas_appid = $request->saas_appid;
        $MassageShop = MassageShop::where(['id' => $request->use_shop_id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageShop) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $tel = [];
            if ($D['tel1']) {
                $tel[] = $D['tel1'];
            }
            if ($D['tel2']) {
                $tel[] = $D['tel2'];
            }
            if ($D['tel3']) {
                $tel[] = $D['tel3'];
            }
            $D['tel'] = $tel;
            $D['mch_id'] = $MassageShop->mch_id;
            hpValidate(ValidateMassageShop::class, $D, 'admin_update');
            $MassageShop->title = $D['title'];
            list($province_id, $city_id, $area_id, $street_id) = $D['regions'];
            $MassageShop->province_id = (int)$province_id;
            $MassageShop->province = MassageRegions::where(['id' => $province_id])->value('title');
            $MassageShop->city_id = $city_id;
            $MassageShop->city = MassageRegions::where(['id' => $city_id])->value('title');
            $MassageShop->area_id = $area_id;
            $MassageShop->area = MassageRegions::where(['id' => $area_id])->value('title');
            if ($street_id) {
                $MassageShop->street_id = $street_id;
                $MassageShop->street = MassageRegions::where(['id' => $street_id])->value('title');
            } else {
                $MassageShop->street_id = null;
                $MassageShop->street = '';
            }
            try {
                $AMap=new AMap($request->saas_appid);
                $geo = $AMap->geo([
                    'address' => "{$MassageShop->province}{$MassageShop->city}{$MassageShop->area}{$MassageShop->street}{$MassageShop->address}{$MassageShop->title}"
                ]);
                if($geo){
                    $location=explode(',',$geo['location']);
                    $MassageShop->latitude=$location[0];
                    $MassageShop->longitude=$location[1];
                }
            } catch (\Throwable $th) {
            }
            Db::startTrans();
            try {
                $MassageShop->logo = $D['logo'][0];
                $MassageShop->address = $D['address'];
                $MassageShop->name = $D['name'];
                $MassageShop->mobile = $D['mobile'];
                $MassageShop->tel = $tel;
                $MassageShop->save();
                Db::commit();
                return $this->success('保存成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('title', 'input', '门店名称', '', [
            'col' => 12,
        ]);
        $builder->addComponent('logo', 'uploadify', '门店logo', '', [
            'col' => 12,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('tel1', 'input', '门店联系电话1', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel2', 'input', '门店联系电话2', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel3', 'input', '门店联系电话3', '', [
            'col' => 12,
        ]);
        $regions = MassageRegions::getCache($saas_appid);
        $builder->addRow('regions', 'city', '地区', [], [
            'col' => 12,
            'options' => $regions,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ]
        ]);
        $builder->addRow('address', 'input', '详细地址', '', [
            'col' => 12,
        ]);
        $builder->addDivider('负责人信息');
        $builder->addRow('name', 'input', '负责人', '', [
            'col' => 12,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
        ]);
        $regions = [
            $MassageShop->province_id,
            $MassageShop->city_id,
            $MassageShop->area_id
        ];
        if ($MassageShop->street_id) {
            $regions[] = $MassageShop->street_id;
        }
        $MassageShop->regions = $regions;
        if ($MassageShop->tel) {
            foreach ($MassageShop->tel as $key => $value) {
                $MassageShop->{'tel' . ($key + 1)} = $value;
            }
        }
        $data = $builder->setData($MassageShop)->create();
        return $this->successRes($data);
    }
    public function thumbGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addTopButton('add', '添加图片', [
            'api'       => $this->pluginPrefix . '/shop/User/thumbCreate',
            'path' => '/User/thumbCreate',
            'type'      => 'modal'
        ], [
            'title' => '添加图片',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('del', '删除', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/shop/User/thumbDelete',
            'method' => 'delete'
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'error',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumnEle('url', '图片', [
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumnEle('examine', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions()
                ],
            ]);
        return $this->successRes($builder->create());
    }
    public function thumb(Request $request)
    {
        if ($request->use_mch_id) {
            return $this->buildMchThubm($request);
        } else {
            return $this->buildShopThubm($request);
        }
    }
    public function buildMchThubm(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['img.saas_appid', '=', $request->saas_appid]
        ];
        $where[] = ['img.mch_id', '=', $request->use_mch_id];
        $data = MassageMchThumb::where($where)
            ->alias('img')
            ->join('MassageMch m', 'm.id = img.mch_id')
            ->order('img.create_time desc')
            ->field('img.*,m.title')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
            });
        return $this->successRes($data);
    }
    public function buildShopThubm(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['img.saas_appid', '=', $request->saas_appid]
        ];
        $where[] = ['img.shop_id', '=', $request->use_shop_id];
        $data = MassageShopThumb::where($where)
            ->alias('img')
            ->join('MassageShop s', 's.id = img.shop_id')
            ->order('img.create_time desc')
            ->field('img.*,s.title')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
            });
        return $this->successRes($data);
    }
    public function thumbCreate(Request $request)
    {
        $saas_appid = $request->saas_appid;
        if ($request->method() === 'POST') {
            $D = $request->post();
            if (empty($D['thumb'])) {
                return $this->fail('请上传图片');
            }
            Db::startTrans();
            try {
                if ($request->use_mch_id) {
                    $model = MassageMch::where(['id' => $request->use_mch_id])->find();
                    $MassageMchThumb = new MassageMchThumb();
                    $thumb = [];
                    foreach ($D['thumb'] as $key => $value) {
                        $temp = [
                            'mch_id' => $model->id,
                            'saas_appid' => $saas_appid,
                            'url' => $value,
                        ];
                        krsort($temp);
                        $thumb[] = $temp;
                    }
                    $MassageMchThumb->saveAll($thumb);
                } else {
                    $model = MassageShop::where(['id' => $request->use_shop_id])->find();
                    $MassageShopThumb = new MassageShopThumb;
                    $thumb = [];
                    foreach ($D['thumb'] as $key => $value) {
                        $temp = [
                            'shop_id' => $model->id,
                            'saas_appid' => $saas_appid,
                            'url' => $value,
                        ];
                        krsort($temp);
                        $thumb[] = $temp;
                    }
                    $MassageShopThumb->saveAll($thumb);
                }
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            return $this->success('添加成功');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('thumb', 'uploadify', '图片', '', [
            'col' => 24,
            'props' => [
                'type' => 'image',
                'limit' => 99,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function qrcode(Request $request)
    {
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        if ($request->use_mch_id) {
            $url = $domain . "/app/ycMassage/#/technician/pages/user/apply?appid={$request->saas_appid}&mch_id={$request->use_mch_id}";
        } else {
            $url = $domain . "/app/ycMassage/#/technician/pages/user/apply?appid={$request->saas_appid}&shop_id={$request->use_shop_id}";
        }
        $builder = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($url)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(400)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->validateResult(false);
        $result = $builder->build();
        return $this->successRes([
            'base64' => 'data:image/png;base64,' . base64_encode($result->getString()),
            'url' => $url
        ]);
    }
}
